package com.wjn.basic.thread.threadpool;


import org.apache.tomcat.util.threads.TaskThreadFactory;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import java.util.concurrent.*;

/**
 * 1.线程的4种创建方式
 * 2.获取线程执行返回值
 */
public class ThreadPoolDemo extends Thread{



    //创建固定大小的线程池
    private static ExecutorService executorfixed = Executors.newFixedThreadPool(5);
    //创建缓存线程池
    private static ExecutorService executorcache = Executors.newCachedThreadPool();
    //创建单个线程池，主要用于执行  先进先出等任务
    private static ExecutorService executorsingle = Executors.newSingleThreadExecutor();
    //创建定时线程池
    private static ExecutorService executorscheduled = Executors.newScheduledThreadPool(15);

    public static void main(String[] args) {


        //固定的线程池执行
//        for(int i=0;i<10;i++){
//            executorfixed.submit(()->{
//                System.out.println("固定的线程执行");
//                try {
//                    System.out.println("睡眠3s");
//                    Thread.sleep(3000);
//
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            });
//        }

        //缓存的线程池,可扩容的执行，最大扩容到 Integer.MAX_VALUE
//        for(int i=0;i<10;i++){
//            executorcache.submit(()->{
//                System.out.println("线程执行");
//                try {
//                    System.out.println("睡眠3s");
//                    Thread.sleep(3000);
//
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            });//有返回值，execute没有返回值
//        }


        //固定的线程池执行
        for(int i=0;i<10;i++){
            executorsingle.submit(()->{
                System.out.println("单例的线程执行");
                try {
                    System.out.println("睡眠3s");
                    Thread.sleep(3000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }



        //获取线程返回值
        FutureTask<Integer> submit2 = (FutureTask<Integer>) executorfixed.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("submit_2");
                return 2;
            }
        });


        FutureTask<Integer> submit3=(FutureTask<Integer>)executorfixed.submit(()->{return 3;});

        try {
           System.out.println("result=" + submit2.get());
           System.out.println("result=" + submit3.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        System.out.println("线程执行");
    }
}
